'''
Created on 18/08/2012

@author: Nrai
'''
import sys

def palette_parser_dispatcher(palette_file):
    
    '''palette_parser_dispatcher(palette_file) - > Dispatches a palette file to the proper palette parser'''
    
    file_extension = palette_file.name.split(".")[1]
    try:
        parser = getattr(sys.modules[__name__], "{ext}_palette_parser".format(ext=file_extension))
        return parser(palette_file)
    except AttributeError:
        raise AttributeError, "Unknown palette format"
        
        
def act_palette_parser(act_file, channels=3, act_length=768):
    '''
        Parses an .act file as a nested list of colors with 3 ints for each channel.
        For standardization purposes the Alpha color should default to index [0]        
    '''
    try:
        rsof, reof = 0, 2                       # relative file positions, used to avoid magic numbers
        act_file.seek(rsof, reof)               # offset relative to the end of file
        assert act_file.tell() == act_length    # .act files always have length 768
    except AssertionError:
        raise IOError, "Corrupt or Invalid .act file"
    act_file.seek(rsof)                         # offset back to absolute file positioning
    try:
        palette = [[ord(channel) for channel in color] for color in (act_file.read(channels) for x in xrange(act_length / channels))]
    except (TypeError, IOError, IndexError):
        raise TypeError, "Error parsing the act file"
    return palette
    
if __name__ == "__main__":
    p = open("C://Documents and Settings//Nrai//Escritorio//a.act")
    act = palette_parser_dispatcher(p)
    print act
        
        
    